package playground.fs.rnkrsoft;

/*-
 * #%L
 * A File Scanner App
 * %%
 * Copyright (C) 2017 - 2020 OSGL (Open Source General Library)
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by test on 2020/3/5.
 */
public class ResultSort {
    /**
     * 排序
     *
     * @param task 将所有子任务合并后的结果，进行排序
     */
    public List<String> sort(FindTaskResult task) {
        Result[] results = convert(task);
        Arrays.sort(results);
        List<String> list = new ArrayList<>();
        for (Result result : results) {
            list.add(result.getCount() + " " + result.getContent());
        }
        return list;
    }

    Result[] convert(FindTaskResult task) {
        Result[] results = new Result[task.getResult().size()];
        int index = 0;
        for (Map.Entry<String, Integer> entry : task.getResult().entrySet()){
            results[index++] = new Result(entry.getKey(), entry.getValue());
        }
        //TODO 将task转换未result对象
        return results;
    }

    static class Result implements Comparable<Result> {
        String content;
        int count;

        public String getContent() {
            return content;
        }

        public int getCount() {
            return count;
        }

        public Result(String content, int count) {
            this.content = content;
            this.count = count;
        }

        @Override
        public int compareTo(Result o) {
            if (o.getCount() > getCount()){
                return 1;
            }else if (o.getCount() == getCount()){
                return o.getContent().compareTo(getContent());
            }else{
                return -1;
            }
        }
    }
}
